using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace MatrixFramework.Shared.Domain.Photos.Search
{
    /// <summary>
    /// 照片搜索优化实体
    /// 用于管理搜索性能优化和索引维护
    /// </summary>
    public class PhotoSearchOptimization : FullAuditedEntity<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 优化类型
        /// </summary>
        public virtual OptimizationType OptimizationType { get; protected set; }

        /// <summary>
        /// 优化状态
        /// </summary>
        public virtual OptimizationStatus Status { get; protected set; }

        /// <summary>
        /// 优化优先级
        /// </summary>
        public virtual OptimizationPriority Priority { get; protected set; }

        /// <summary>
        /// 优化范围
        /// </summary>
        public virtual OptimizationScope Scope { get; protected set; }

        /// <summary>
        /// 优化目标
        /// </summary>
        public virtual List<OptimizationTarget> Targets { get; protected set; }

        /// <summary>
        /// 优化参数
        /// </summary>
        public virtual Dictionary<string, object> Parameters { get; protected set; }

        /// <summary>
        /// 优化配置
        /// </summary>
        public virtual OptimizationConfiguration Configuration { get; protected set; }

        /// <summary>
        /// 计划执行时间
        /// </summary>
        public virtual DateTime? ScheduledTime { get; protected set; }

        /// <summary>
        /// 开始执行时间
        /// </summary>
        public virtual DateTime? StartTime { get; protected set; }

        /// <summary>
        /// 完成时间
        /// </summary>
        public virtual DateTime? CompletionTime { get; protected set; }

        /// <summary>
        /// 执行耗时（毫秒）
        /// </summary>
        public virtual long ExecutionDuration { get; protected set; }

        /// <summary>
        /// 优化结果
        /// </summary>
        public virtual OptimizationResult Result { get; protected set; }

        /// <summary>
        /// 性能指标
        /// </summary>
        public virtual PerformanceMetrics PerformanceMetrics { get; protected set; }

        /// <summary>
        /// 索引统计
        /// </summary>
        public virtual IndexStatistics IndexStatistics { get; protected set; }

        /// <summary>
        /// 优化历史
        /// </summary>
        public virtual List<OptimizationHistory> History { get; protected set; }

        /// <summary>
        /// 优化日志
        /// </summary>
        public virtual List<OptimizationLog> Logs { get; protected set; }

        protected PhotoSearchOptimization()
        {
            Targets = new List<OptimizationTarget>();
            Parameters = new Dictionary<string, object>();
            Configuration = new OptimizationConfiguration();
            Result = new OptimizationResult();
            PerformanceMetrics = new PerformanceMetrics();
            IndexStatistics = new IndexStatistics();
            History = new List<OptimizationHistory>();
            Logs = new List<OptimizationLog>();
        }

        public PhotoSearchOptimization(
            Guid id,
            OptimizationType optimizationType,
            OptimizationScope scope = OptimizationScope.All,
            List<OptimizationTarget> targets = null,
            Dictionary<string, object> parameters = null,
            Guid? tenantId = null) : base(id)
        {
            OptimizationType = optimizationType;
            Scope = scope;
            Targets = targets ?? new List<OptimizationTarget>();
            Parameters = parameters ?? new Dictionary<string, object>();
            TenantId = tenantId;
            Status = OptimizationStatus.Pending;
            Priority = OptimizationPriority.Normal;

            Configuration = new OptimizationConfiguration();
            Result = new OptimizationResult();
            PerformanceMetrics = new PerformanceMetrics();
            IndexStatistics = new IndexStatistics();
            History = new List<OptimizationHistory>();
            Logs = new List<OptimizationLog>();
        }

        /// <summary>
        /// 开始优化
        /// </summary>
        public virtual void StartOptimization()
        {
            if (Status != OptimizationStatus.Pending && Status != OptimizationStatus.Retrying)
                throw new InvalidOperationException($"无法在状态 {Status} 下开始优化");

            Status = OptimizationStatus.Running;
            StartTime = DateTime.Now;
            AddLog(OptimizationLogLevel.Info, "开始搜索优化", $"优化类型: {OptimizationType}, 优化范围: {Scope}");
        }

        /// <summary>
        /// 完成优化
        /// </summary>
        public virtual void CompleteOptimization(OptimizationResult result, long executionDuration)
        {
            Status = OptimizationStatus.Completed;
            CompletionTime = DateTime.Now;
            ExecutionDuration = executionDuration;
            Result = result ?? new OptimizationResult();

            // 更新性能指标
            PerformanceMetrics.UpdateMetrics(this);

            AddLog(OptimizationLogLevel.Info, "搜索优化完成", $"耗时: {executionDuration}ms, 结果: {result.IsSuccess}");
        }

        /// <summary>
        /// 优化失败
        /// </summary>
        public virtual void FailOptimization(string errorMessage)
        {
            Status = OptimizationStatus.Failed;
            Result.IsSuccess = false;
            Result.ErrorMessage = errorMessage;
            AddLog(OptimizationLogLevel.Error, "搜索优化失败", errorMessage);
        }

        /// <summary>
        /// 取消优化
        /// </summary>
        public virtual void CancelOptimization(string reason = null)
        {
            Status = OptimizationStatus.Cancelled;
            Result.CancelReason = reason;
            AddLog(OptimizationLogLevel.Warning, "搜索优化已取消", reason);
        }

        /// <summary>
        /// 暂停优化
        /// </summary>
        public virtual void PauseOptimization(string reason = null)
        {
            if (Status != OptimizationStatus.Running)
                throw new InvalidOperationException($"无法在状态 {Status} 下暂停优化");

            Status = OptimizationStatus.Paused;
            AddLog(OptimizationLogLevel.Info, "搜索优化已暂停", reason);
        }

        /// <summary>
        /// 恢复优化
        /// </summary>
        public virtual void ResumeOptimization()
        {
            if (Status != OptimizationStatus.Paused)
                throw new InvalidOperationException($"无法在状态 {Status} 下恢复优化");

            Status = OptimizationStatus.Running;
            AddLog(OptimizationLogLevel.Info, "搜索优化已恢复");
        }

        /// <summary>
        /// 添加优化目标
        /// </summary>
        public virtual void AddTarget(OptimizationTarget target)
        {
            if (target != null)
            {
                Targets.Add(target);
            }
        }

        /// <summary>
        /// 移除优化目标
        /// </summary>
        public virtual void RemoveTarget(Guid targetId)
        {
            Targets.RemoveAll(t => t.Id == targetId);
        }

        /// <summary>
        /// 更新参数
        /// </summary>
        public virtual void UpdateParameters(Dictionary<string, object> parameters)
        {
            Parameters = parameters ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 设置参数
        /// </summary>
        public virtual void SetParameter(string key, object value)
        {
            Parameters[key] = value;
        }

        /// <summary>
        /// 更新配置
        /// </summary>
        public virtual void UpdateConfiguration(OptimizationConfiguration configuration)
        {
            Configuration = configuration ?? new OptimizationConfiguration();
        }

        /// <summary>
        /// 设置计划执行时间
        /// </summary>
        public virtual void SetScheduledTime(DateTime scheduledTime)
        {
            ScheduledTime = scheduledTime;
        }

        /// <summary>
        /// 添加优化日志
        /// </summary>
        public virtual void AddLog(OptimizationLogLevel level, string message, string details = null)
        {
            var log = new OptimizationLog
            {
                Level = level,
                Message = message,
                Details = details,
                LogTime = DateTime.Now
            };

            Logs.Add(log);
        }

        /// <summary>
        /// 添加优化历史
        /// </summary>
        public virtual void AddHistory(OptimizationAction action, string description)
        {
            var history = new OptimizationHistory
            {
                Action = action,
                Description = description,
                ActionTime = DateTime.Now
            };

            History.Add(history);
        }

        /// <summary>
        /// 更新索引统计
        /// </summary>
        public virtual void UpdateIndexStatistics(IndexStatistics statistics)
        {
            IndexStatistics = statistics ?? new IndexStatistics();
        }

        /// <summary>
        /// 检查是否可以执行
        /// </summary>
        public virtual bool CanExecute()
        {
            return Status == OptimizationStatus.Pending || Status == OptimizationStatus.Retrying;
        }

        /// <summary>
        /// 检查是否已完成
        /// </summary>
        public virtual bool IsCompleted()
        {
            return Status == OptimizationStatus.Completed ||
                   Status == OptimizationStatus.Failed ||
                   Status == OptimizationStatus.Cancelled;
        }

        /// <summary>
        /// 获取优化摘要
        /// </summary>
        public virtual OptimizationSummary GetSummary()
        {
            return new OptimizationSummary
            {
                OptimizationType = OptimizationType,
                Status = Status,
                Scope = Scope,
                TargetCount = Targets.Count,
                ExecutionDuration = ExecutionDuration,
                IsSuccess = Result.IsSuccess,
                PerformanceImprovement = PerformanceMetrics.GetImprovementPercentage(),
                LastOptimizationTime = CompletionTime,
                IndexSize = IndexStatistics.TotalIndexSize,
                IndexFragmentation = IndexStatistics.FragmentationLevel
            };
        }
    }

    /// <summary>
    /// 优化类型枚举
    /// </summary>
    public enum OptimizationType
    {
        /// <summary>
        /// 索引重建
        /// </summary>
        IndexRebuild = 0,

        /// <summary>
        /// 索引优化
        /// </summary>
        IndexOptimization = 1,

        /// <summary>
        /// 查询优化
        /// </summary>
        QueryOptimization = 2,

        /// <summary>
        /// 缓存优化
        /// </summary>
        CacheOptimization = 3,

        /// <summary>
        /// 数据库优化
        /// </summary>
        DatabaseOptimization = 4,

        /// <summary>
        /// 内存优化
        /// </summary>
        MemoryOptimization = 5,

        /// <summary>
        /// 搜索引擎优化
        /// </summary>
        SearchEngineOptimization = 6,

        /// <summary>
        /// 索引碎片整理
        /// </summary>
        IndexDefragmentation = 7,

        /// <summary>
        /// 索引统计更新
        /// </summary>
        IndexStatisticsUpdate = 8,

        /// <summary>
        /// 热点分析优化
        /// </summary>
        HotspotAnalysisOptimization = 9,

        /// <summary>
        /// 自动调优
        /// </summary>
        AutoTuning = 10,

        /// <summary>
        /// 性能分析
        /// </summary>
        PerformanceAnalysis = 11,

        /// <summary>
        /// 查询计划优化
        /// </summary>
        QueryPlanOptimization = 12,

        /// <summary>
        /// 全文搜索优化
        /// </summary>
        FullTextSearchOptimization = 13,

        /// <summary>
        /// 相似度搜索优化
        /// </summary>
        SimilaritySearchOptimization = 14,

        /// <summary>
        /// 地理搜索优化
        /// </summary>
        GeographicSearchOptimization = 15,

        /// <summary>
        /// 时间序列搜索优化
        /// </summary>
        TimeSeriesSearchOptimization = 16
    }

    /// <summary>
    /// 优化状态枚举
    /// </summary>
    public enum OptimizationStatus
    {
        /// <summary>
        /// 等待中
        /// </summary>
        Pending = 0,

        /// <summary>
        /// 运行中
        /// </summary>
        Running = 1,

        /// <summary>
        /// 已暂停
        /// </summary>
        Paused = 2,

        /// <summary>
        /// 已完成
        /// </summary>
        Completed = 3,

        /// <summary>
        /// 失败
        /// </summary>
        Failed = 4,

        /// <summary>
        /// 已取消
        /// </summary>
        Cancelled = 5,

        /// <summary>
        /// 重试中
        /// </summary>
        Retrying = 6,

        /// <summary>
        /// 超时
        /// </summary>
        Timeout = 7,

        /// <summary>
        /// 部分完成
        /// </summary>
        PartiallyCompleted = 8
    }

    /// <summary>
    /// 优化优先级枚举
    /// </summary>
    public enum OptimizationPriority
    {
        /// <summary>
        /// 低优先级
        /// </summary>
        Low = 0,

        /// <summary>
        /// 普通优先级
        /// </summary>
        Normal = 1,

        /// <summary>
        /// 高优先级
        /// </summary>
        High = 2,

        /// <summary>
        /// 紧急优先级
        /// </summary>
        Urgent = 3,

        /// <summary>
        /// 关键优先级
        /// </summary>
        Critical = 4
    }

    /// <summary>
    /// 优化范围枚举
    /// </summary>
    public enum OptimizationScope
    {
        /// <summary>
        /// 全部
        /// </summary>
        All = 0,

        /// <summary>
        /// 索引
        /// </summary>
        IndexOnly = 1,

        /// <summary>
        /// 查询
        /// </summary>
        QueryOnly = 2,

        /// <summary>
        /// 缓存
        /// </summary>
        CacheOnly = 3,

        /// <summary>
        /// 数据库
        /// </summary>
        DatabaseOnly = 4,

        /// <summary>
        /// 内存
        /// </summary>
        MemoryOnly = 5,

        /// <summary>
        /// 搜索引擎
        /// </summary>
        SearchEngineOnly = 6,

        /// <summary>
        /// 自定义范围
        /// </summary>
        Custom = 7
    }

    /// <summary>
    /// 优化目标
    /// </summary>
    public class OptimizationTarget
    {
        /// <summary>
        /// 目标ID
        /// </summary>
        public Guid Id { get; set; } = Guid.NewGuid();

        /// <summary>
        /// 目标类型
        /// </summary>
        public TargetType TargetType { get; set; }

        /// <summary>
        /// 目标名称
        /// </summary>
        public string TargetName { get; set; }

        /// <summary>
        /// 目标值
        /// </summary>
        public object TargetValue { get; set; }

        /// <summary>
        /// 当前值
        /// </summary>
        public object CurrentValue { get; set; }

        /// <summary>
        /// 优化目标
        /// </summary>
        public string OptimizationGoal { get; set; }

        /// <summary>
        /// 优先级
        /// </summary>
        public int Priority { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;

        /// <summary>
        /// 目标权重
        /// </summary>
        public double Weight { get; set; } = 1.0;

        /// <summary>
        /// 期望改进比例
        /// </summary>
        public double ExpectedImprovementPercentage { get; set; }

        /// <summary>
        /// 实际改进比例
        /// </summary>
        public double ActualImprovementPercentage { get; set; }

        /// <summary>
        /// 是否达到目标
        /// </summary>
        public bool IsTargetAchieved => ActualImprovementPercentage >= ExpectedImprovementPercentage;

        /// <summary>
        /// 目标详情
        /// </summary>
        public Dictionary<string, object> Details { get; set; } = new();
    }

    /// <summary>
    /// 目标类型枚举
    /// </summary>
    public enum TargetType
    {
        /// <summary>
        /// 查询响应时间
        /// </summary>
        QueryResponseTime = 0,

        /// <summary>
        /// 索引大小
        /// </summary>
        IndexSize = 1,

        /// <summary>
        /// 索引命中率
        /// </summary>
        IndexHitRate = 2,

        /// <summary>
        /// 缓存命中率
        /// </summary>
        CacheHitRate = 3,

        /// <summary>
        /// 内存使用率
        /// </summary>
        MemoryUsage = 4,

        /// <summary>
        /// CPU使用率
        /// </summary>
        CpuUsage = 5,

        /// <summary>
        /// 磁盘I/O
        /// </summary>
        DiskIO = 6,

        /// <summary>
        /// 网络延迟
        /// </summary>
        NetworkLatency = 7,

        /// <summary>
        /// 并发处理能力
        /// </summary>
        Concurrency = 8,

        /// <summary>
        /// 索引碎片率
        /// </summary>
        IndexFragmentation = 9,

        /// <summary>
        /// 查询复杂度
        /// </summary>
        QueryComplexity = 10,

        /// <summary>
        /// 搜索准确性
        /// </summary>
        SearchAccuracy = 11,

        /// <summary>
        /// 相关性评分
        /// </summary>
        RelevanceScore = 12,

        /// <summary>
        /// 自定义指标
        /// </summary>
        CustomMetric = 13
    }

    /// <summary>
    /// 优化配置
    /// </summary>
    public class OptimizationConfiguration
    {
        /// <summary>
        /// 是否启用自动优化
        /// </summary>
        public bool EnableAutoOptimization { get; set; } = true;

        /// <summary>
        /// 优化间隔（小时）
        /// </summary>
        public int OptimizationIntervalHours { get; set; } = 24;

        /// <summary>
        /// 最大执行时间（分钟）
        /// </summary>
        public int MaxExecutionTimeMinutes { get; set; } = 60;

        /// <summary>
        /// 是否在低峰期执行
        /// </summary>
        public bool ExecuteInOffPeakHours { get; set; } = true;

        /// <summary>
        /// 低峰时间段
        /// </summary>
        public List<TimeRange> OffPeakHours { get; set; } = new();

        /// <summary>
        /// 是否允许中断
        /// </summary>
        public bool AllowInterruption { get; set; } = true;

        /// <summary>
        /// 是否创建备份
        /// </summary>
        public bool CreateBackup { get; set; } = true;

        /// <summary>
        /// 备份保留天数
        /// </summary>
        public int BackupRetentionDays { get; set; } = 7;

        /// <summary>
        /// 资源限制
        /// </summary>
        public ResourceLimits ResourceLimits { get; set; } = new();

        /// <summary>
        /// 通知配置
        /// </summary>
        public NotificationConfig NotificationConfig { get; set; } = new();

        /// <summary>
        /// 质量阈值
        /// </summary>
        public QualityThresholds QualityThresholds { get; set; } = new();

        /// <summary>
        /// 调优策略
        /// </summary>
        public TuningStrategy TuningStrategy { get; set; } = new();
    }

    /// <summary>
    /// 时间范围
    /// </summary>
    public class TimeRange
    {
        /// <summary>
        /// 开始时间
        /// </summary>
        public TimeSpan StartTime { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public TimeSpan EndTime { get; set; }

        /// <summary>
        /// 检查时间是否在范围内
        /// </summary>
        public bool IsInRange(DateTime time)
        {
            var timeOfDay = time.TimeOfDay;
            return timeOfDay >= StartTime && timeOfDay <= EndTime;
        }
    }

    /// <summary>
    /// 资源限制
    /// </summary>
    public class ResourceLimits
    {
        /// <summary>
        /// 最大内存使用量（MB）
        /// </summary>
        public long MaxMemoryMB { get; set; } = 2048;

        /// <summary>
        /// 最大CPU使用率（百分比）
        /// </summary>
        public double MaxCpuUsage { get; set; } = 80;

        /// <summary>
        /// 最大磁盘IO（MB/s）
        /// </summary>
        public double MaxDiskIOMBS { get; set; } = 100;

        /// <summary>
        /// 最大网络带宽（MB/s）
        /// </summary>
        public double MaxNetworkBandwidthMBS { get; set; } = 50;

        /// <summary>
        /// 最大并发连接数
        /// </summary>
        public int MaxConcurrentConnections { get; set; } = 10;
    }

    /// <summary>
    /// 通知配置
    /// </summary>
    public class NotificationConfig
    {
        /// <summary>
        /// 是否启用通知
        /// </summary>
        public bool EnableNotifications { get; set; } = true;

        /// <summary>
        /// 开始时通知
        /// </summary>
        public bool NotifyOnStart { get; set; } = false;

        /// <summary>
        /// 完成时通知
        /// </summary>
        public bool NotifyOnCompletion { get; set; } = true;

        /// <summary>
        /// 失败时通知
        /// </summary>
        public bool NotifyOnFailure { get; set; } = true;

        /// <summary>
        /// 里程碑通知
        /// </summary>
        public bool NotifyOnMilestones { get; set; } = false;

        /// <summary>
        /// 通知渠道
        /// </summary>
        public List<string> NotificationChannels { get; set; } = new();

        /// <summary>
        /// 通知邮箱列表
        /// </summary>
        public List<string> NotificationEmails { get; set; } = new();

        /// <summary>
        /// 通知模板
        /// </summary>
        public Dictionary<string, string> NotificationTemplates { get; set; } = new();
    }

    /// <summary>
    /// 质量阈值
    /// </summary>
    public class QualityThresholds
    {
        /// <summary>
        /// 最小查询响应时间（毫秒）
        /// </summary>
        public int MinQueryResponseTimeMs { get; set; } = 100;

        /// <summary>
        /// 最大查询响应时间（毫秒）
        /// </summary>
        public int MaxQueryResponseTimeMs { get; set; } = 5000;

        /// <summary>
        /// 最小索引命中率
        /// </summary>
        public double MinIndexHitRate { get; set; } = 0.8;

        /// <summary>
        /// 最小缓存命中率
        /// </summary>
        public double MinCacheHitRate { get; set; = } = 0.7;

        /// <summary>
        /// 最大索引碎片率
        /// </summary>
        public double MaxIndexFragmentationRate { get; set; } = 0.3;

        /// <summary>
        /// 最小搜索准确性
        /// </summary>
        public double MinSearchAccuracy { get; set; } = 0.9;

        /// <summary>
        /// 最小相关性评分
        /// </summary>
        public double MinRelevanceScore { get; set; } = 0.7;
    }

    /// <summary>
    /// 调优策略
    /// </summary>
    public class TuningStrategy
    {
        /// <summary>
        /// 是否启用自动调优
        /// </summary>
        public bool EnableAutoTuning { get; set; } = true;

        /// <summary>
        /// 学习算法
        /// </summary>
        public string LearningAlgorithm { get; set; } = "ReinforcementLearning";

        /// <summary>
        /// 机器学习模型
        /// </summary>
        public string MachineLearningModel { get; set; } = "NeuralNetwork";

        /// <summary>
        /// 历史数据保留天数
        /// </summary>
        public int HistoricalDataRetentionDays { get; set; } = 30;

        /// <summary>
        /// 模型训练间隔（天）
        /// </summary>
        public int ModelTrainingIntervalDays { get; set; } = 7;

        /// <summary>
        /// A/B测试启用
        /// </summary>
        public bool EnableABTesting { get; set; } = false;

        /// <summary>
        /// 实验配置
        /// </summary>
        public List<ExperimentConfig> Experiments { get; set; } = new();

        /// <summary>
        /// 预测模型
        /// </summary>
        public PredictionModel PredictionModel { get; set; } = new();
    }

    /// <summary>
    /// 实验配置
    /// </summary>
    public class ExperimentConfig
    {
        /// <summary>
        /// 实验名称
        /// </summary>
        public string ExperimentName { get; set; }

        /// <summary>
        /// 实验类型
        /// </summary>
        public string ExperimentType { get; set; }

        /// <summary>
        /// 流量分配比例
        /// </summary>
        public double TrafficSplitRatio { get; set; }

        /// <summary>
        /// 实验持续时间（天）
        /// </summary>
        public int DurationDays { get; set; }

        /// <summary>
        /// 成功指标
        /// </summary>
        public List<string> SuccessMetrics { get; set; } = new();

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;
    }

    /// <summary>
    /// 预测模型
    /// </summary>
    public class PredictionModel
    {
        /// <summary>
        /// 模型类型
        /// </summary>
        public string ModelType { get; set; }

        /// <summary>
        /// 模型版本
        /// </summary>
        public string ModelVersion { get; set; }

        /// <summary>
        /// 模型文件路径
        /// </summary>
        public string ModelFilePath { get; set; }

        /// <summary>
        /// 模型准确率
        /// </summary>
        public double Accuracy { get; set; }

        /// <summary>
        /// 最后训练时间
        /// </summary>
        public DateTime? LastTrainingTime { get; set; }

        /// <summary>
        /// 预测特征
        /// </summary>
        public List<string> PredictionFeatures { get; set; } = new();

        /// <summary>
        /// 模型参数
        /// </summary>
        public Dictionary<string, object> ModelParameters { get; set; } = new();
    }

    /// <summary>
    /// 优化结果
    /// </summary>
    public class OptimizationResult
    {
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// 取消原因
        /// </summary>
        public string CancelReason { get; set; }

        /// <summary>
        /// 优化的目标数量
        /// </summary>
        public int OptimizedTargetsCount { get; set; }

        /// <summary>
        /// 达成目标的数量
        /// </summary>
        public int AchievedTargetsCount { set; get; }

        /// <summary>
        /// 目标达成率
        /// </summary>
        public double TargetAchievementRate => OptimizedTargetsCount > 0 ? (double)AchievedTargetsCount / OptimizedTargetsCount : 0;

        /// <summary>
        /// 执行耗时
        /// </summary>
        public long ExecutionDuration { get; set; }

        /// <summary>
        /// 优化详情
        /// </summary>
        public Dictionary<string, object> Details { get; set; } = new();

        /// <summary>
        /// 改进指标
        /// </summary>
        public List<ImprovementMetric> ImprovementMetrics { get; set; } = new();

        /// <summary>
        /// 警告信息
        /// </summary>
        public List<string> Warnings { get; set; } = new();

        /// <summary>
        /// 建议操作
        /// </summary>
        public List<string> RecommendedActions { get; set; } = new();

        /// <summary>
        /// 下次优化建议时间
        /// </summary>
        public DateTime? NextOptimizationTime { get; set; }
    }

    /// <summary>
    /// 改进指标
    /// </summary>
    public class ImprovementMetric
    {
        /// <summary>
        /// 指标名称
        /// </summary>
        public string MetricName { get; set; }

        /// <summary>
        /// 优化前值
        /// </summary>
        public double BeforeValue { get; set; }

        /// <summary>
        /// 优化后值
        /// </summary>
        public double AfterValue { get; set; }

        /// <summary>
        /// 改进比例
        /// </summary>
        public double ImprovementPercentage { get; set; }

        /// <summary>
        /// 改进状态
        /// </summary>
        public ImprovementStatus ImprovementStatus { get; set; }

        /// <summary>
        /// 单位
        /// </summary>
        public string Unit { get; set; }

        /// <summary>
        /// 描述
        /// </summary>
        public string Description { get; set; }
    }

    /// <summary>
    /// 改进状态枚举
    /// </summary>
    public enum ImprovementStatus
    {
        /// <summary>
        /// 改进
        /// </summary>
        Improved = 0,

        /// <summary>
        /// 恶化
        /// </summary>
        Degraded = 1,

        /// <summary>
        /// 无变化
        /// </summary>
        NoChange = 2,

        /// <summary>
        /// 显著改进
        /// </summary>
        SignificantlyImproved = 3,

        /// <summary>
        /// 显著恶化
        /// </summary>
        SignificantlyDegraded = 4
    }

    /// <summary>
    /// 性能指标
    /// </summary>
    public class PerformanceMetrics
    {
        /// <summary>
        /// 优化前查询响应时间（毫秒）
        /// </summary>
        public double BeforeQueryResponseTimeMs { get; set; }

        /// <summary>
        /// 优化后查询响应时间（毫秒）
        /// </summary>
        public double AfterQueryResponseTimeMs { get; set; }

        /// <summary>
        /// 优化前索引命中率
        /// </summary>
        public double BeforeIndexHitRate { get; set; }

        /// <summary>
        /// 优化后索引命中率
        /// </summary>
        public double AfterIndexHitRate { get; set; }

        /// <summary>
        /// 优化前缓存命中率
        /// </summary>
        public double BeforeCacheHitRate { get; set; }

        /// <summary>
        /// 优化后缓存命中率
        /// </summary>
        public double AfterCacheHitRate { get; set; }

        /// <summary>
        /// 优化前内存使用量（MB）
        /// </summary>
        public double BeforeMemoryUsageMB { get; set; }

        /// <summary>
        /// 优化后内存使用量（MB）
        /// </summary>
        public double AfterMemoryUsageMB { get; set; }

        /// <summary>
        /// 优化前CPU使用率
        /// </summary>
        public double BeforeCpuUsage { get; set; }

        /// <summary>
        /// 优化后CPU使用率
        /// </summary>
        public double AfterCpuUsage { get; set; }

        /// <summary>
        /// 优化前吞吐量（请求/秒）
        /// </summary>
        public double BeforeThroughput { get; set; }

        /// <summary>
        /// 优化后吞吐量（请求/秒）
        /// </summary>
        public double AfterThroughput { get; set; }

        /// <summary>
        /// 优化前并发用户数
        /// </summary>
        public int BeforeConcurrentUsers { get; set; }

        /// <summary>
        /// 优化后并发用户数
        /// </summary>
        public int AfterConcurrentUsers { get; set; }

        /// <summary>
        /// 更新性能指标
        /// </summary>
        public void UpdateMetrics(PhotoSearchOptimization optimization)
        {
            // 这里应该根据实际的优化结果更新指标
            // 在实际实现中，需要从数据库或其他数据源获取优化前后的性能数据
        }

        /// <summary>
        /// 获取改进百分比
        /// </summary>
        public double GetImprovementPercentage()
        {
            var improvements = new List<double>();

            if (BeforeQueryResponseTimeMs > 0 && AfterQueryResponseTimeMs > 0)
            {
                var improvement = (BeforeQueryResponseTimeMs - AfterQueryResponseTimeMs) / BeforeQueryResponseTimeMs * 100;
                improvements.Add(improvement);
            }

            if (BeforeIndexHitRate > 0 && AfterIndexHitRate > 0)
            {
                var improvement = (AfterIndexHitRate - BeforeIndexHitRate) / BeforeIndexHitRate * 100;
                improvements.Add(improvement);
            }

            if (BeforeCacheHitRate > 0 && AfterCacheHitRate > 0)
            {
                var improvement = (AfterCacheHitRate - BeforeCacheHitRate) / BeforeCacheHitRate * 100;
                improvements.Add(improvement);
            }

            if (improvements.Count > 0)
                return improvements.Average();

            return 0;
        }

        /// <summary>
        /// 获取性能摘要
        /// </summary>
        public PerformanceSummary GetSummary()
        {
            return new PerformanceSummary
            {
                QueryResponseTimeImprovement = BeforeQueryResponseTimeMs > 0 ?
                    ((BeforeQueryResponseTimeMs - AfterQueryResponseTimeMs) / BeforeQueryResponseTimeMs * 100) : 0,
                IndexHitRateImprovement = BeforeIndexHitRate > 0 ?
                    ((AfterIndexHitRate - BeforeIndexHitRate) / BeforeIndexHitRate * 100) : 0,
                CacheHitRateImprovement = BeforeCacheHitRate > 0 ?
                    ((AfterCacheHitRate - BeforeCacheHitRate) / BeforeCacheHitRate * 100) : 0,
                ThroughputImprovement = BeforeThroughput > 0 ?
                    ((AfterThroughput - BeforeThroughput) / BeforeThroughput * 100) : 0,
                ConcurrencyImprovement = AfterConcurrentUsers - BeforeConcurrentUsers,
                MemoryUsageChange = AfterMemoryUsageMB - BeforeMemoryUsageMB,
                CpuUsageChange = AfterCpuUsage - BeforeCpuUsage
            };
        }
    }

    /// <summary>
    /// 性能摘要
    /// </summary>
    public class PerformanceSummary
    {
        /// <summary>
        /// 查询响应时间改进（百分比）
        /// </summary>
        public double QueryResponseTimeImprovement { get; set; }

        /// <summary>
        /// 索引命中率改进（百分比）
        /// </summary>
        public double IndexHitRateImprovement { get; set; }

        /// <summary>
        /// 缓存命中率改进（百分比）
        /// </summary>
        public double CacheHitRateImprovement { get; set; }

        /// <summary>
        /// 吞吐量改进（百分比）
        /// </summary>
        public double ThroughputImprovement { get; set; }

        /// <summary>
        /// 并发能力改进
        /// </summary>
        public int ConcurrencyImprovement { get; set; }

        /// <summary>
        /// 内存使用变化（MB）
        /// </summary>
        public double MemoryUsageChange { get; set; }

        /// <summary>
        /// CPU使用变化
        /// </summary>
        public double CpuUsageChange { get; set; }

        /// <summary>
        /// 总体改进评分
        /// </summary>
        public double OverallImprovementScore => CalculateOverallScore();

        /// <summary>
        /// 计算总体改进评分
        /// </summary>
        private double CalculateOverallScore()
        {
            var scores = new List<double>
            {
                QueryResponseTimeImprovement,
                IndexHitRateImprovement,
                CacheHitRateImprovement,
                ThroughputImprovement
            };

            // 过滤掉负值，只计算正面的改进
            var positiveScores = scores.Where(s => s > 0).ToList();

            return positiveScores.Count > 0 ? positiveScores.Average() : 0;
        }
    }

    /// <summary>
    /// 索引统计
    /// </summary>
    public class IndexStatistics
    {
        /// <summary>
        /// 总索引数量
        /// </summary>
        public int TotalIndexCount { get; set; }

        /// <summary>
        /// 总索引大小（字节）
        /// </summary>
        public long TotalIndexSize { get; set; }

        /// <summary>
        /// 活跃索引数量
        /// </summary>
        public int ActiveIndexCount { get; set; }

        /// <summary>
        /// 空闲索引数量
        /// </summary>
        public int IdleIndexCount { get; set; }

        /// <summary>
        /// 碎片化索引数量
        /// </summary>
        public int FragmentedIndexCount { get; set; }

        /// <summary>
        /// 碎片化级别
        /// </summary>
        public double FragmentationLevel { get; set; }

        /// <summary>
        /// 平均索引深度
        /// </summary>
        public double AverageIndexDepth { get; set; }

        /// <summary>
        /// 最大索引深度
        /// </summary>
        public int MaxIndexDepth { get; set; }

        /// <summary>
        /// 索引条目总数
        /// </summary>
        public long TotalIndexEntries { get; set; }

        /// <summary>
        /// 活跃索引条目数
        /// </summary>
        public long ActiveIndexEntries { get; set; }

        /// <summary>
        /// 最后更新时间
        /// </summary>
        public DateTime? LastUpdateTime { get; set; }

        /// <summary>
        /// 索引状态分布
        /// </summary>
        public Dictionary<string, int> IndexStatusDistribution { get; set; } = new();

        /// <summary>
        /// 索引类型分布
        /// </summary>
        public Dictionary<string, int> IndexTypeDistribution { get; set; } = new();

        /// <summary>
        /// 获取索引健康评分
        /// </summary>
        public double GetHealthScore()
        {
            var healthFactors = new List<double>
            {
                // 活跃索引比例
                TotalIndexCount > 0 ? (double)ActiveIndexCount / TotalIndexCount : 0,
                // 碎片化程度（越低越好）
                Math.Max(0, 1 - FragmentationLevel),
                // 平均深度合理性
                AverageIndexDepth <= 10 ? 1.0 : 0.5
            };

            return healthFactors.Count > 0 ? healthFactors.Average() * 100 : 0;
        }

        /// <summary>
        /// 获取优化建议
        /// </summary>
        public List<string> GetOptimizationSuggestions()
        {
            var suggestions = new List<string>();

            if (FragmentationLevel > 0.3)
            {
                suggestions.Add("索引碎片化严重，建议执行索引整理");
            }

            if (IdleIndexCount > ActiveIndexCount * 0.5)
            {
                suggestions.Add("空闲索引过多，建议清理不必要的索引");
            }

            if (AverageIndexDepth > 10)
            {
                suggestions.Add("索引深度过深，建议优化索引结构");
            }

            if (TotalIndexEntries > 10000000 && ActiveIndexCount < TotalIndexCount * 0.7)
            {
                suggestions.Add("索引条目过多，建议优化索引策略");
            }

            return suggestions;
        }
    }

    /// <summary>
    /// 优化历史
    /// </summary>
    public class OptimizationHistory
    {
        /// <summary>
        /// 操作类型
        /// </summary>
        public OptimizationAction Action { get; set; }

        /// <summary>
        /// 操作描述
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// 操作时间
        /// </summary>
        public DateTime ActionTime { get; set; }

        /// <summary>
        /// 操作者ID
        /// </summary>
        public Guid? OperatorId { get; set; }

        /// <summary>
        /// 操作者名称
        /// </summary>
        public string OperatorName { get; set; }

        /// <summary>
        /// 操作前状态
        /// </summary>
        public string BeforeState { get; set; }

        /// <summary>
        /// 操作后状态
        /// </summary>
        public string AfterState { get; set; }

        /// <summary>
        /// 影响的索引列表
        /// </summary>
        public List<string> AffectedIndexes { get; set; } = new();

        /// <summary>
        /// 额外数据
        /// </summary>
        public Dictionary<string, object> AdditionalData { get; set; } = new();
    }

    /// <summary>
    /// 优化操作枚举
    /// </summary>
    public enum OptimizationAction
    {
        /// <summary>
        /// 创建
        /// </summary>
        Created = 0,

        /// <summary>
        /// 开始
        /// </summary>
        Started = 1,

        /// <summary>
        /// 暂停
        /// </summary>
        Paused = 2,

        /// <summary>
        /// 恢复
        /// </summary>
        Resumed = 3,

        /// <summary>
        /// 完成
        /// </summary>
        Completed = 4,

        /// <summary>
        /// 失败
        /// </summary>
        Failed = 5,

        /// <summary>
        /// 取消
        /// </summary>
        Cancelled = 6,

        /// <summary>
        /// 重试
        /// </summary>
        Retry = 7,

        /// <summary>
        /// 索引创建
        /// </summary>
        IndexCreated = 8,

        /// <summary>
        /// 索引更新
        /// </summary>
        IndexUpdated = 9,

        /// <summary>
        /// 索引删除
        /// </summary>
        IndexDeleted = 10,

        /// <summary>
        /// 索引重建
        /// </summary>
        IndexRebuilt = 11,

        /// <summary>
        /// 索引优化
        /// </summary>
        IndexOptimized = 12,

        /// <summary>
        /// 缓存清理
        /// </summary>
        CacheCleared = 13,

        /// <summary>
        /// 配置更新
        /// </summary>
        ConfigurationUpdated = 14,

        /// <summary>
        /// 性能分析
        /// </summary>
        PerformanceAnalyzed = 15
    }

    /// <summary>
    /// 优化日志
    /// </summary>
    public class OptimizationLog
    {
        /// <summary>
        /// 日志级别
        /// </summary>
        public OptimizationLogLevel Level { get; set; }

        /// <summary>
        /// 日志消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 详细信息
        /// </summary>
        public string Details { get; set; }

        /// <summary>
        /// 日志时间
        /// </summary>
        public DateTime LogTime { get; set; }

        /// <summary>
        /// 相关组件
        /// </summary>
        public string Component { get; set; }

        /// <summary>
        /// 相关索引
        /// </summary>
        public string RelatedIndex { get; set; }

        /// <summary>
        /// 性能数据
        /// </summary>
        public Dictionary<string, object> PerformanceData { get; set; } = new();

        /// <summary>
        /// 异常信息
        /// </summary>
        public string Exception { get; set; }

        /// <summary>
        /// 堆栈跟踪
        /// </summary>
        public string StackTrace { get; set; }
    }

    /// <summary>
    /// 优化日志级别枚举
    /// </summary>
    public enum OptimizationLogLevel
    {
        /// <summary>
        /// 调试
        /// </summary>
        Debug = 0,

        /// <summary>
        /// 信息
        /// </summary>
        Info = 1,

        /// <summary>
        /// 警告
        /// </summary>
        Warning = 2,

        /// <summary>
        /// 错误
        /// </summary>
        Error = 3,

        /// <summary>
        /// 致命错误
        /// </summary>
        Fatal = 4
    }

    /// <summary>
    /// 优化摘要
    /// </summary>
    public class OptimizationSummary
    {
        /// <summary>
        /// 优化类型
        /// </summary>
        public OptimizationType OptimizationType { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public OptimizationStatus Status { get; set; }

        /// <summary>
        /// 范围
        /// </summary>
        public OptimizationScope Scope { get; set; }

        /// <summary>
        /// 目标数量
        /// </summary>
        public int TargetCount { get; set; }

        /// <summary>
        /// 执行耗时
        /// </summary>
        public long ExecutionDuration { get; set; }

        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 性能改进百分比
        /// </summary>
        public double PerformanceImprovement { get; set; }

        /// <summary>
        /// 最后优化时间
        /// </summary>
        public DateTime? LastOptimizationTime { get; set; }

        /// <summary>
        /// 索引大小
        /// </summary>
        public long IndexSize { get; set; }

        /// <summary>
        /// 索引碎片化程度
        /// </summary>
        public double IndexFragmentation { get; set; }

        /// <summary>
        /// 状态描述
        /// </summary>
        public string StatusDescription => GetStatusDescription();

        /// <summary>
        /// 获取状态描述
        /// </summary>
        private string GetStatusDescription()
        {
            return Status switch
            {
                OptimizationStatus.Pending => "等待中",
                OptimizationStatus.Running => "运行中",
                OptimizationStatus.Paused => "已暂停",
                OptimizationStatus.Completed => "已完成",
                OptimizationStatus.Failed => "失败",
                OptimizationStatus.Cancelled => "已取消",
                OptimizationStatus.Retrying => "重试中",
                OptimizationStatus.Timeout => "超时",
                OptimizationStatus.PartiallyCompleted => "部分完成",
                _ => "未知状态"
            };
        }
    }
}